package com.amazon.shop.aop;

import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.OperationLogService;
import com.amazon.shop.utils.CommonResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 操作日志切面类
 *
 * @Author 郭非
 * @Date 2021/6/15
 * @Time 10:32
 * @Version 1.0
 */
@Aspect
@Component
public class SystemLogAspect {
    @Resource
    private OperationLogService operationLogService;

    /**
     * 切点指向自定义注解
     */
    @Pointcut("@annotation(com.amazon.shop.aop.SystemLog)")
    public void logPointCut() {

    }

    /**
     * 环绕通知
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        CommonResult proceed = (CommonResult) joinPoint.proceed();
        try {
            //获取编号信息
            String classString = proceed.get("list").getClass().toString();
            //获取业务员信息
            String salesman = (String) proceed.get("salesman");
            //批量增加日志
            if ("class java.util.ArrayList".equals(classString)) {
                List<String> list = (List<String>) proceed.get("list");
                //方法执行之后保存
                operationLogService.saveOperationLogBatch(joinPoint, list, salesman);
            } else {
                String id = (String) proceed.get("list");
                operationLogService.saveOperationLog(joinPoint, id, salesman);
            }
        } catch (Exception e) {
            throw new CustomException(ReturnConstant.NO_LOG_NUMBER_ERROR_CODE
                    , ReturnConstant.NO_LOG_NUMBER_ERROR_MESSAGE);
        }
        //调用方法保存日志
        return proceed;
    }
}
